package com.atguigu.es.client;

import com.atguigu.es.beans.Emp;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.core.*;

import java.io.IOException;

/**
 * Created by Smexy on 2022/5/21
 *
 *      JestClient: 客户端对象
 *
 *              构造：
 *                          new 构造器()
 *                  设计模式:
 *                          工厂模式 :    A a= new AFactory().getA()
 *                          建造者模式：   A a = new ABuilder().build()
 *
 *       Action: 要执行的命令
 *              读: Search
 *
 *              写:  Index
 *                   Delete
 *
 *              批量写： Bulk
 */
public class BulkDemo {

    public static void main(String[] args) throws IOException {

        //创建客户端
        JestClientFactory jestClientFactory = new JestClientFactory();

        // 连接server端
        HttpClientConfig httpClientConfig = (new HttpClientConfig.Builder("http://hadoop102:9200")).build();

        jestClientFactory.setHttpClientConfig(httpClientConfig);

        JestClient jestClient = jestClientFactory.getObject();

        // 准备要批量操作的命令
        Delete delete = new Delete.Builder("20").index("test").type("emps").build();
        Emp emp = new Emp("1001", "jack", "男", "吃饭", 20, 333.33);
        Index index1 = new Index.Builder(emp).index("test").type("emps").id("41").build();
        Index index2 = new Index.Builder(emp).index("test").type("emps").id("42").build();

        // 加入到bulk中
        Bulk bulk = new Bulk.Builder().addAction(delete).addAction(index1).addAction(index2).build();

        // 执行命令
        BulkResult execute = jestClient.execute(bulk);

        // 如果是读，解析server返回的结果
        System.out.println("执行失败数:"+execute.getFailedItems().size());

        // 关闭客户端
        jestClient.close();

    }


}
